package com.cafe.action.admin;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.apache.struts2.ServletActionContext;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;

import com.cafe.exception.CafeException;
import com.cafe.model.Product;
import com.cafe.model.ProductCategory;
import com.cafe.model.ProductFile;
import com.cafe.service.ProductCategoryService;
import com.cafe.service.ProductService;
import com.malamute.core.action.CrudMethod;
import com.malamute.system.action.system.SingleUploadAction;

/**
 * @author Aceguan
 * @description 菜谱Acion
 * @date 2012-2-26 下午08:15:26
 * @version v1.0
 */
public class ProductAction extends SingleUploadAction implements CrudMethod {
	private Product product;
	private List<ProductCategory> productCategoryList;
	@Autowired
	private ProductService productService;
	@Autowired
	private ProductCategoryService productCategoryService;
	private List<Integer> productIds;

	private boolean isSoldOut;

	public static final String URL_DIR = "/file/product";

	// ACE:这里路径最好可以使用可配置的
	private static final String foldenPath = ServletActionContext
			.getServletContext().getRealPath(URL_DIR);

	public void prepare() throws Exception {
		File saveDir = new File(foldenPath);
		if (!saveDir.exists()) {
			saveDir.mkdirs();
		}
	}

	public void prepareForm() throws Exception {
		DetachedCriteria criteria = DetachedCriteria
				.forClass(ProductCategory.class);
		productCategoryList = productCategoryService
				.listAllProductCategory(criteria);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @return
	 * 
	 * @throws Exception
	 * 
	 * @see com.malamute.core.action.CrudMethod#save()
	 */
	@Override
	public String save() throws Exception {
		// debug模式下会显示
		if (log.isDebugEnabled()) {
			log.info("开始封装上传文件");
			log.info("upload:" + upload);
			log.info("uploadFileName:" + uploadFileName);
			log.info("uploadFileContentType:" + uploadContentType);
		}
		// Set<FileInSystem> files = new HashSet();
		if (upload == null) {
			throw new CafeException("upload error");
		} else {
			// log.info(ServletActionContext.getServletContext().getRealPath("/"));
			// log.info(request.getContextPath());
			// log.info(".............." + foldenPath);
			ProductFile productFile = new ProductFile();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddkkmmss");
			String fileName = sdf.format(new Date()) + uploadFileName;
			String fileLocation = foldenPath + "\\" + fileName;
			String urlPath = URL_DIR + "/" + fileName;
			copyFile(upload.getAbsolutePath(), fileLocation);
			productFile.setName(uploadFileName);// 文件名称
			productFile.setContentType(uploadContentType);// 文件类型
			productFile.setPath(fileLocation);
			productFile.setProduct(product);
			productFile.setUrlPath(urlPath);
			product.setProductFile(productFile);
			// for (int i = 0; i < uploads.size(); i++) {
			// fileInSystem = new FileInSystem();
			// SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddkkmmss");
			// String fileName = sdf.format(new Date())
			// + uploadFileNames.get(i);
			// String fileLocation = foldenPath + "\\" + PRODUCT_TYPE_PRFEX
			// + fileName;
			// copyFile(uploads.get(i).getAbsolutePath(), fileLocation);
			// fileInSystem.setName(uploadFileNames.get(i));// 文件名称
			// fileInSystem.setContentType(uploadContentTypes.get(i));// 文件类型
			// fileInSystem.setPath(fileLocation);// 真实保存地址
			// // ACE:注意 这里必须将关联set进去，这样才可以自动保存关联
			// fileInSystem.setProduct(product);
			// files.add(fileInSystem);
			// }
		}

		// product.setFiles(files);
		productService.saveProduct(product);
		return ACTION;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @return
	 * 
	 * @throws Exception
	 * 
	 * @see com.malamute.core.action.CrudMethod#update()
	 */
	@Override
	public String update() throws Exception {
		// 这里有问题
		Product tmp;
		if (product != null && product.getId() != 0) {
			tmp = productService.getProductById(product.getId());
			ProductFile productFile = tmp.getProductFile();

			// 存在下载时
			if (upload != null) {
				// log.info(ServletActionContext.getServletContext().getRealPath("/"));
				// log.info(request.getContextPath());
				// log.info(".............." + foldenPath);
				SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddkkmmss");
				String fileName = sdf.format(new Date()) + uploadFileName;
				String fileLocation = foldenPath + "\\" + fileName;
				String urlPath = URL_DIR + "/" + fileName;
				copyFile(upload.getAbsolutePath(), fileLocation);

				productFile.setName(uploadFileName);// 文件名称
				productFile.setContentType(uploadContentType);// 文件类型
				productFile.setPath(fileLocation);
				productFile.setUrlPath(urlPath);
				tmp.setProductFile(productFile);

			}
			tmp.setProductCategory(product.getProductCategory());
			tmp.setName(product.getName());
			tmp.setPrice(product.getPrice());
			tmp.setDescription(product.getDescription());
			productService.updateProduct(tmp);
		}
		return ACTION;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @return
	 * 
	 * @throws Exception
	 * 
	 * @see com.malamute.core.action.CrudMethod#input()
	 */
	@Override
	public String form() throws Exception {
		if (product != null) {
			setProduct(productService.getProductById(product.getId()));
		}
		return FORM;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @return
	 * 
	 * @throws Exception
	 * 
	 * @see com.malamute.core.action.CrudMethod#list()
	 */
	@Override
	public String list() throws Exception {
		DetachedCriteria criteria = DetachedCriteria.forClass(Product.class);
		if (searchParam.keySet().isEmpty()) {
			criteria.add(Restrictions.eq("isSoldOut", false));
			isSoldOut = false;
		}
		for (Iterator it = searchParam.keySet().iterator(); it.hasNext();) {
			String key = (String) it.next();
			String[] values = (String[]) searchParam.get(key);
			if (key.indexOf("is") != -1) {
				isSoldOut = Boolean.valueOf(values[0]);
				criteria.add(Restrictions.eq(key, isSoldOut));

			} else {
				criteria.add(Restrictions.like(key, "%" + values[0] + "%"));
			}

		}
		// TODO :这里又可以做修改了。。跳转页面按照默认规则
		// setListResult("customer_main");
		// page.setCurrentPageNum(1);
		productService.listProductsByPage(criteria, page);
		return LIST;
	}

	public String sellOut() {
		productService.soldOutProducts(productIds);
		return ACTION;
	}

	public String onSell() {
		productService.onSellProducts(productIds);
		return ACTION;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @return
	 * 
	 * @throws Exception
	 * 
	 * @see com.malamute.core.action.CrudMethod#search()
	 */
	@Override
	public String search() throws Exception {
		return this.list();
	}

	public Product getProduct() {
		return product;
	}

	public void setProduct(Product product) {
		this.product = product;
	}

	public List<ProductCategory> getProductCategoryList() {
		return productCategoryList;
	}

	public void setProductCategoryList(List<ProductCategory> productCategoryList) {
		this.productCategoryList = productCategoryList;
	}

	public List<Integer> getProductIds() {
		return productIds;
	}

	public void setProductIds(List<Integer> productIds) {
		this.productIds = productIds;
	}

	public boolean isSoldOut() {
		return isSoldOut;
	}

	public void setSoldOut(boolean isSoldOut) {
		this.isSoldOut = isSoldOut;
	}

}
